package com.baizhi;

import com.baizhi.realm.CustomerRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

public class TestCustomerMd5RealmAuthenicator {
    public static void main(String[] args) {
        // 创建securityManager
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        CustomerRealm realm = new CustomerRealm();
//
//        //设置realm使用hash凭证匹配器
//        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//        hashedCredentialsMatcher.setHashAlgorithmName("md5");
//        hashedCredentialsMatcher.setHashIterations(1024);
//        realm.setCredentialsMatcher(hashedCredentialsMatcher);

        defaultSecurityManager.setRealm(realm);

        // 设置自定义realm
        defaultSecurityManager.setRealm(realm);
        // 将安全工具类设置安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        // 通过安全工具类获取subject
        Subject subject = SecurityUtils.getSubject();
        // 创建token
        UsernamePasswordToken token = new UsernamePasswordToken("xiaomiao", "123");
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        }



        //认证用户进行授权
        if(subject.isAuthenticated()){
//基于角色的权限控制
      System.out.println(subject.hasRole("super"));
      // 基于多角色权限控制
      System.out.println(subject.hasAllRoles(Arrays.asList("admin","user")));
        }
    System.out.println("====================");
    // 基于权限字符串的访问控制 资源标识符：操作：资源类型
    System.out.println("权限"+subject.isPermitted("user:*:01"));
    System.out.println("权限"+subject.isPermitted("product:create"));
    }
}
